package com.elitel.frame.core.common;

import java.io.File;
import java.io.IOException;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

public class FileUtil {

    public static File createFolder(String path) {
        File file = new File(path);
        if (!file.exists() || file.isDirectory()) {
            file.mkdirs();
        }
        return file;
    }

    public static File createFolder(File file) {
        if (!file.exists() || file.isDirectory()) {
            file.mkdirs();
        }
        return file;
    }

    public static File saveFile(MultipartFile file, String savePath,
                                String saveName) throws IOException {
        File pathFile = new File(savePath);
        File saveFile = new File(pathFile, saveName);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        FileCopyUtils.copy(file.getBytes(), saveFile);
        return saveFile;
    }


    public static boolean delete(String path) {
        File file = new File(path);
        if (file.isFile() && file.exists()) {
            return file.delete();
        }
        return false;
    }

    public static String getFileSuffix(File file) {
        return getFileSuffix(file.getName());
    }

    public static String getFileSuffix(String fileName) {
        int lastIndex = fileName.lastIndexOf(".");
        if (lastIndex != -1 && lastIndex != fileName.length() - 1) {
            return fileName.substring(lastIndex + 1);
        }
        return null;
    }
}
